package tasks

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/gocelery/gocelery"
	"github.com/gomodule/redigo/redis"
	"time"
)

//启动gocelery
func init() {
	task_broker := beego.AppConfig.String("task_broker")
	task_worker, err := beego.AppConfig.Int("task_worker")
	if err != nil {
		task_worker = 5
	}
	redisPool := &redis.Pool{
		MaxIdle:     16,  // 池中空闲连接的最大数量
		MaxActive:   0,   // 在给定时间内由池分配的最大连接数
		IdleTimeout: 300, // 在此期间保持空闲后关闭连接
		Dial: func() (redis.Conn, error) {
			c, err := redis.DialURL(task_broker)
			if err != nil {
				return nil, err
			}
			return c, err
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}

	// initialize celery client
	Cli, _ := gocelery.NewCeleryClient(
		gocelery.NewRedisBroker(redisPool),
		&gocelery.RedisCeleryBackend{Pool: redisPool},
		task_worker, // number of workers
	)

	// register task
	Cli.Register("task.SetHostConnect", SetHostConnect)
	Cli.Register("task.SyncAssetInfo", GetHostInfo)
	Cli.Register("task.CodeRelease", CodeRelease)
	Cli.Register("task.DeployScript", DeployScript)
	Cli.Register("task.UpdateTestServer", UpdateTestServer)

	// start workers (non-blocking call)
	Cli.StartWorker()

	//定时任务
	// tk1 := toolbox.NewTask("mytask", "*/1 * * * * *", tadd)
	// toolbox.AddTask("myTask", tk1)
	//    toolbox.StartTask()
	//log := logs.NewLogger()
	//beego.SetLogger("file", `{"filename":"/opt/ops/src/test.log"}`)
	//logs.SetLogger("file", `{"filename":"/opt/ops/src/test.log"}`)
	logs.EnableFuncCallDepth(true)
	logs.Info("celery start")

}
